using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Data;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SAE.Common
{
    public class ProfileHelper
    {
        public static string LogFileDirectoryPath = AppDomain.CurrentDomain.BaseDirectory + "Logs\\";

        public static void Import( string siteUrl,string fileName)
        {
            string logFileName = LogFileDirectoryPath + DateTime.Now.ToString("yyyy-MM-dd-hh-mm") + ".txt";

            try
            {
                 SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(siteUrl))
                    {
                        ServerContext context = ServerContext.GetContext(site);

                        UserProfileManager profileManager = new UserProfileManager(context);                   

                        XmlDocument xDoc = new XmlDocument();
                        xDoc.Load(fileName);

                        foreach (XmlNode profileNode in xDoc.SelectNodes("Profiles//Profile"))
                        {
                            string accountName = profileNode.SelectSingleNode("AccountName").InnerText;

                            UserProfile up=null;

                            if (profileManager.UserExists(accountName))
                            {
                                up = profileManager.GetUserProfile(accountName);
                            }
                            else
                            {
                                up = profileManager.CreateUserProfile(accountName);
                            }

                            foreach (Microsoft.Office.Server.UserProfiles.Property property in profileManager.Properties)
                            {
                                if (property.IsAdminEditable)
                                {
                                    string value = GetAttributeValue(profileNode, property.Name);

                                    if (!string.IsNullOrEmpty(value))
                                    {
                                        up[property.Name].Value = value;
                                        
                                    }
                                }
                            }

                            up.Commit();
                        }
                    }
                });
            }
            catch (Exception ex)
            {               
                 Common.LogUtility.AppendLog(logFileName, ": General error occured, error message:" + ex.Message);
            }
        }

        public static void Export(string siteUrl,string fileName)
        {
            using (Microsoft.SharePoint.SPSite site = new Microsoft.SharePoint.SPSite(siteUrl))
            {
                Microsoft.Office.Server.ServerContext context = Microsoft.Office.Server.ServerContext.GetContext(site);

                Microsoft.Office.Server.UserProfiles.UserProfileManager profileManager = new Microsoft.Office.Server.UserProfiles.UserProfileManager(context);

                DataTable dtProfile = new DataTable("Profile");

                foreach (Microsoft.Office.Server.UserProfiles.Property property in profileManager.Properties)
                {
                    dtProfile.Columns.Add(new DataColumn(property.Name, typeof(string)));
                }

                foreach (UserProfile up in profileManager)
                {
                    DataRow row = dtProfile.NewRow();

                    foreach (Microsoft.Office.Server.UserProfiles.Property property in profileManager.Properties)
                    {
                        if (up[property.Name].Value != null)
                        {
                            row[property.Name] = up[property.Name].Value;
                        }
                    }

                    dtProfile.Rows.Add(row);
                }

                DataSet dsProfile = new DataSet("Profiles");
                dsProfile.Tables.Add(dtProfile);

                dsProfile.WriteXml(fileName);
            }
        }

        /// <summary>
        /// Gets the attribute value.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <param name="attributeName">Name of the attribute.</param>
        /// <returns></returns>
        private static string GetAttributeValue(XmlNode property, string attributeName)
        {
            if (property.SelectSingleNode(attributeName) != null)
            {
                return property.SelectSingleNode(attributeName).InnerText;
            }
            else
            {
                return string.Empty;
            }
        }
    }
}
